package com.bjpowernode.oa.web.action;

import com.bjpowernode.oa.util.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DeptDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String deptno=request.getParameter("deptno");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out= response.getWriter();
        Connection con=null;
        PreparedStatement pstmt=null;
        ResultSet rs=null;
        int count=0;
        try {
            con= DBUtil.getConnection();
            con.setAutoCommit(false);
            String sql="delete from dept where deptno=?";
            pstmt=con.prepareStatement(sql);
            pstmt.setInt(1,Integer.parseInt(deptno));
            count=pstmt.executeUpdate();
            con.commit();
        } catch (SQLException e) {
            if(con!=null){
                try {
                    con.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(con,pstmt,rs);
        }
        if(count==1){
//            request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/dept/list");
        }else{
//            request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(request.getContextPath()+"/error.html");
        }
    }
}
